jQuery.fn.sheetManage = function(method) {
   var methods = {
      init: function() { },
      initQuestionForm: function(options) {
         var quesform = this;

         if(quesform.data(":initialized"))
            return;

         quesform.data(":initialized", true);

         // hide error first
         $(".error", quesform).hide();

         // correct answer click addclass
         $("input[name='correctanswer']", quesform).click(function(){
            var p_div = $(this).parent().parent();
            var s_input = $("input[name='singleanswer[]']", p_div);
            // remove the others class
            $("input[name='singleanswer[]']", quesform).removeClass();
            s_input.addClass("must_fill");
         });

         $.metadata.setType("attr", "validate");
         quesform.validate({
            submitHandler: function(form) {
               $(form).ajaxSubmit({
                     dataType: "json",
                     beforeSubmit: function(data, form, options) {
                        var question_type = $("input[name='typeid']",form).val();
                        if (question_type == 1) {
                           var singleanswers = $("input[name='singleanswer[]']",form).filter(function(i) {
                             return $.trim($(this).val()).length > 0;
                           });

                           if(singleanswers.length <2) {
                             $("#errormsg", form).jobUtil("showError", "请输入至少两个选项！");
                             return false;
                           }

                           if ($.trim($(".must_fill",form).val()).length <= 0) {
                              $("#errormsg", form).jobUtil("showError", "正确答案的选项内容不能为空！");
                              return false;
                           };
                        }

                        if(!showLoading(form))
                           return false;
                        $(".error", form).hide();
                     },
                     success: function(data) {
                        if(data.error) {
                           $("#errormsg", form).jobUtil("showError", data.error);
                        }
                        else if(data.success) {
                           $("#errormsg", form).html(data.success).addClass("success").
                           fadeIn('fast', function() {
                              /* refresh data */
                              $.ajaxSetup({cache:false});
                              quesform.fadeOut('fast', function() {
                                 $('#each_ques_info_'+options.qid).show();
                                 $(".error", form).html('').hide();

                                 $.ajax({
                                    type: "GET",
                                    url: OC.filePath('jobposition', 'ajax', 'getquestion.php'),
                                    data: {job_id: options.job_id, sheet_id: options.sheet_id, qid: options.qid},
                                    dataType: 'html',
                                    success: function(result){
                                       $('#each_ques_info_'+options.qid).html(result).show();
                                    }
                                 });

                              });
                           });
                        }
                     }
               });
            }
         });

         // Handle cancel link action and active button at the end
         $(".adpresetbtn", quesform).click(function(e) {
            quesform.fadeOut('fast', function(){
               $(".error", quesform).html('').hide();
               $('#each_ques_info_'+options.qid).fadeIn('fast');
            });
         });
         $('.submit_btn', quesform).prop('disabled',false);
      }
   };

   if (methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
   } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
   } else {
      $.error( 'Method ' +  method + ' does not exist on jobProfile' );
   }

};

$(document).ready(function($) {
   // Edit sheet basic info trigger
   $(".adp_rightname #edit_sheet").click(function(){
      var target = $(this);
      $.metadata.setType("attr", "data");
      var data = target.metadata();
      var real_data = target.data();

      if (real_data.sheet_id) {
         $("#addsheetform input[name='sheet_id']").val(real_data.sheet_id);
         $("#addsheetform input[name='title']").val(real_data.title);
         $("#addsheetform input[name='totaltime']").val(real_data.totaltime);
      } else if (data.sheet_id) {
         $("#addsheetform input[name='sheet_id']").val(data.sheet_id);
         $("#addsheetform input[name='title']").val(data.title);
         $("#addsheetform input[name='totaltime']").val(data.totaltime);
      }
      $('.adp_setaction .adp_rightname').hide();
      $('#addsheetform').show();
   });

   $("#addsheetform #submit_button").click(function(){
      $('#addsheetform #title').focus();
   });

   // Add sheet basic info action
   $("#addsheetform").validate({
      rules: {
         title: {
            required: true,
            rangelength: [5,20]
         },
         totaltime: {
            required: true,
            digits: true,
            min: 1
         }
      },
      messages: {
         title: {
            required: "请输入试卷名称",
            rangelength: "请输入5~20个字符"
         },
         totaltime: {
            required: "请输入答题时长",
            digits: "请输入数字",
            min: "答题时长请填写正整数"
         }
      },
      submitHandler: function(form) {
         $("#addsheetform").ajaxSubmit({
            dataType: "json",
               beforeSubmit: function(data, form, options) {
                  if (!showLoading("#addsheetform"))
                     return false;
                  $("#addsheetform .error").hide();
               },
               success: function(data) {
                  try {
                     var retmsg = data;
                     if (retmsg.error) {
                        $("#addsheetform #errormsg").jobUtil("showError", retmsg.error);
                     }
                     if (retmsg.success) {
                        if (retmsg.redirect) {
                           window.location = retmsg.redirect;
                        } else {
                           $("#addsheetform .error").hide();
                           var sheet_id = $("#addsheetform input[name='sheet_id']").val();
                           var title = $("#addsheetform input[name='title']").val();
                           var totaltime = $("#addsheetform input[name='totaltime']").val();

                           $(".adp_rightname #edit_sheet").data('sheet_id', sheet_id);
                           $(".adp_rightname #edit_sheet").data('title', title);
                           $(".adp_rightname #edit_sheet").data('totaltime', totaltime);

                           $(".adp_rightname #sheet_title").html(title);
                           $(".adp_rightname #sheet_totaltime").html('('+totaltime+'分钟)');

                           $('#addsheetform').hide();
                           $('.adp_setaction .adp_rightname').show();
                        }
                     }
                  } catch(e) {
                     return false;
                  }
               }
         });
      }
   });

   // Change input type when click different radio
   $('#singleanswer_radio').click(function(){
      $('#freeinput_div textarea').prop('disabled',true);
      $('#singleanswer_div input').prop('disabled',false);
      $('#freeinput_div').hide();
      $('#singleanswer_div').show();
   });
   $('#freeinput_radio').click(function(){
      $('#singleanswer_div input').prop('disabled',true);
      $('#freeinput_div textarea').prop('disabled',false);
      $('#singleanswer_div').hide().find("input.error").removeClass("error");
      $('#freeinput_div').show();
   });

   // Default enable singleanswer area when page loaded
   $('#singleanswer_div').show();
   $('#freeinput_div').hide();
   $('#singleanswer_div input').prop('disabled',false);
   $('#singleanswer_radio').prop('checked','checked');

   // correct answer click addclass
   $("#addquestionform input[name='correctanswer']").click(function(){
      var p_div = $(this).parent().parent();
      var s_input = $("input[name='singleanswer[]']", p_div);
      // remove the others class
      $("#addquestionform input[name='singleanswer[]']").removeClass();
      s_input.addClass("must_fill");
   });

   // Add question basic info action
   $("#addquestionform").validate({
      errorPlacement:function(error,element) {
         if (element.attr("name") == "singleanswer[]" || element.attr("name") == "correctanswer")
            error.insertAfter("#last_choice");
         else if (element.attr("name") == "typeid")
            error.insertAfter("#last_typeid");
         else
            error.insertAfter(element);
      },
      submitHandler: function(form) {
         $(form).ajaxSubmit({
            dataType: "json",
               beforeSubmit: function(data, form, options) {
                  var question_type = $("input[name='typeid']:checked",form).val();
                  if (question_type == 1) {
                     var singleanswers = $("input[name='singleanswer[]']",form).filter(function(i) {
                       return $.trim($(this).val()).length > 0;
                     });

                     if(singleanswers.length <2) {
                       $("#errormsg", form).jobUtil("showError", "请输入至少两个选项！");
                       return false;
                     }

                     if ($.trim($(".must_fill", form).val()).length <= 0) {
                        $("#errormsg", form).jobUtil("showError", "正确答案的选项内容不能为空！");
                        return false;
                     };
                  }

                  if (!showLoading(form))
                     return false;
                  $(".error", form).hide();
               },
               success: function(data) {
                  try {
                     var retmsg = data;
                     if (retmsg.error) {
                        $("#errormsg", form).jobUtil("showError", retmsg.error);
                     }

                     if (retmsg.success) {
                        var qid = retmsg.data.qid;
                        var job_id = retmsg.data.job_id;
                        var sheet_id = retmsg.data.sheet_id;

                        if (retmsg.redirect) {
                           window.location = retmsg.redirect;
                           return;
                        } else {
                           $("#errormsg", form).html(retmsg.success).addClass("success").
                           fadeIn('slow', function() {
                              $(".error", form).html('').removeClass("success").hide();
                              $("#addquestionform")[0].reset();
                           });
                        }

                        // Remove .must_fill class after submit
                        $("input[name='singleanswer[]']",form).removeClass('must_fill');

                        // Render new question html block
                        $.ajax({
                           type: "GET",
                           url: OC.filePath('jobposition', 'ajax', 'getquestion.php'),
                           data: {job_id: job_id, sheet_id: sheet_id, qid: qid, is_new: 1},
                           dataType: 'html',
                           cache: false, 
                           success: function(result) {
                              $("#questions_div").prepend(result);
                           }
                        });

                     }
                  } catch(e) {
                     return false;
                  }
               }
         });
      }
   });

   $('#questions_div').delegate(".eachquestion .papertestdelete", "click", function(e) {
      var target = $(this).closest('.each_ques_block');
      // Data prepare
      $.metadata.setType("attr", "data");
      var mData = target.metadata();
      var data = {};
      data.id = mData.qid;
      data.job_id = mData.job_id;
      data.sheet_id = mData.sheet_id;

      showConfirmDialog('确认删除该试题么？',function() {
         // Delete action
         $.ajax({
            type:"POST",
            url: del_ques_url,
            data:data,
            dataType: "json",
            success:function(data) {
               try {
                  var retmsg = data;
                  if (retmsg.error) {
                     showMessageDialog(retmsg.error);
                     return;
                  }
                  if (retmsg.success) {
                     if (retmsg.redirect) {
                        window.location = retmsg.redirect;
                        return;
                     } else {
                        target.fadeOut('500', function(){
                           target.remove();
                        });
                        return;
                     }
                  }
               } catch(e) {
                  return false;
               }
            }
         });
      });
      return false;
   });

   $('#questions_div').delegate(".eachquestion .papertestedit", "click", function(e) {
      e.stopPropagation();
      var target = $(this).closest('.each_ques_block');
      // Data prepare
      $.metadata.setType("attr", "data");
      var data = target.metadata();

      $('#each_ques_info_'+data.qid).fadeOut('fast', function(){
         $('#each_ques_form_'+data.qid).fadeIn('fast', function() {
            $(this).sheetManage("initQuestionForm", {
               qid: data.qid,
               job_id: data.job_id,
               sheet_id: data.sheet_id,
               test_var: true,
               test_var: false
            });
         });
      });
   });


});
